package spynx.util;

import java.io.File;
import java.io.FileFilter;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.regex.Pattern;

public class Folder extends File {

	private static final long serialVersionUID = 1L;

	public Folder(String pathname) {
		super(new File(pathname).getAbsolutePath());
	}

	public Folder(URI uri) {
		super(uri);
	}

	public Folder(String parent, String child) {
		super(parent, child);
	}

	public Folder(File parent, String child) {
		super(parent, child);
	}

	public List<File> scanFile(String filePattern, boolean recursive) {
		final Pattern pattern = Pattern.compile(filePattern);
		ArrayList<File> list = new ArrayList<File>();
		Queue<File> queue = new LinkedBlockingQueue<File>();
		queue.add(this);
		while (!queue.isEmpty()) {
			File dir = queue.poll();
			File[] files = dir.listFiles(new FileFilter() {
	
				@Override
				public boolean accept(File file) {
					return file.isFile() && pattern.matcher(file.getName()).find();
				}
				
			});
			for(File f: files)
				list.add(f);
			if (recursive) {
				File[] dirs = dir.listFiles(new FileFilter() {

					@Override
					public boolean accept(File arg0) {
						return arg0.isDirectory();
					}
					
				});
				for(File d: dirs)
					queue.add(d);
			}
		}
		return list;
	}
}
